<script setup lang='ts'>
import {ref, reactive, PropType, onBeforeMount, watch} from 'vue'
import {FormRules, ElMessage} from 'element-plus'

import {
  HealthGuideFormInfor,
  saveHealthGuideInfor, icCodeLists, getCodeList
} from '@/api/physicalExaminationManager/healthGuide'
import {DialogType, ColorRed, ColorTheme, SeleteData} from '@/api/config'
import {transfDicArrData, getObjectByKey, Normal} from '@/util/common'

import {FromItem} from '@/components/dFrom/dFrom'
import dDialog from '@/components/dDialog/dDialog.vue'
import dFrom from '@/components/dFrom/dFrom.vue'
import operation from '@/components/dTable/components/operation.vue'
import {HeaderData, Operation as Opr, RowOperbuttons} from '@/components/dTable/dTable'
import dTable from '@/components/dTable/dTable.vue'

import useStore from '@/store/common'
const {store} = useStore.setup()

//是否显示
const props = defineProps({
  //显示
  showDialog:{
    type:Boolean,
    required:true
  },
  //弹窗类型
  dialogType:{
    type:String as PropType<DialogType>,
    required:true
  },
  //数据
  healthGuideData:{
    type:Object as PropType<HealthGuideFormInfor>,
    required:true
  }
})

const emits = defineEmits(['close'])

// 弹窗标题定义
const title = ref('')

// 弹窗标题设置
const initTitle = () => {
  if (props.dialogType === 'add') {
    title.value = '新增健教指导'
  }
  else if (props.dialogType === 'edit') {
    title.value = '编辑健教指导'
  }
}

//信息
const formData:HealthGuideFormInfor = reactive({...props.healthGuideData, icdCodeList:props.healthGuideData.icdCodeList ?? []})

// 显示加载状态
const showSaveLoading = ref(false)

// const checkSmallType = (rule, value, callback) => {
//   if (formData.bigType !== 2 && !value) {
//     return callback(new Error('请选择健教小类'))
//   }
//   callback()
// }

// 表单规则
const rules = reactive<FormRules>({
  name:[
    {required:true, message: '请输入健教名称', trigger: ['change', 'blur']},
    {required:true, message:'长度应不超过50个字符', max:50, trigger: ['change', 'blur']},
    {required:true, message:'应输入汉字、字母、数字、字符', pattern:Normal, trigger:['change', 'blur']}
  ],
  businessType:[
    {required:true, message: '请选择业务类型', trigger: ['change', 'blur']}
  ],
  bigType:[
    {required:true, message: '请选择健教大类', trigger: ['change', 'blur']}
  ],
  smallType:[
    {required:true, message: '请选择健教小类', trigger: ['change', 'blur']}
    // { message: '请选择健教小类', validator: checkSmallType, trigger: ['change', 'blur']}
  ]
})

//表单项
const fromItems = ref<Array<FromItem>>([
  {label:'健教大类', placeholder:'请选择健教大类', prop:'bigType', type:'selete', seleteData:[]},
  {label:'健教小类', placeholder:'请选择健教小类', prop:'smallType', type:'selete', seleteData:[], hideItem:true},
  {label:'业务类型', placeholder:'请选择业务类型', prop:'businessType', type:'selete', seleteData:[]},
  {label:'健教名称', placeholder:'请输入健教名称', prop:'name', type:'input'},
  {label:'ICD-10编码', prop:'icdCodeList', type:'slot', slotName:'codeList'}
])

const smallTypeList = ref<Array<SeleteData>>([])

//西医不需要选择健教小类
watch(() => formData.bigType, newValue => {
  const item = getObjectByKey(fromItems.value, 'prop', 'smallType')
  if (item && item.type === 'selete') {
    if (newValue === 1) {
      item.hideItem = false
      item.seleteData = smallTypeList.value
    } else {
      item.hideItem = true
      formData.smallType = null
      formData.smallTypeName = ''
      item.seleteData = []
    }
  }
}, {
  immediate:true
})

//表单清除控制
const resetFieldsFlag = ref(false)

const validateFlag = ref(false)

// 确认按钮
const onConfirm = () => {
  validateFlag.value = !validateFlag.value
}

//关闭
const onClose = () => {
  emits('close')
  //关闭后清除表单数据以及表单验证数据 可根据具体业务自行调整
  resetFieldsFlag.value = !resetFieldsFlag.value
}

//取消按钮
const onCancel = () => {
  onClose()
}

//表单验证通过事件
const onSubmit = () => {
  showSaveLoading.value = true
  // console.log('formData', formData)

  saveHealthGuideInfor(formData).then(() => {
    showSaveLoading.value = false
    ElMessage.success('保存成功！')
    emits('close')
  }).catch((error) => {
    showSaveLoading.value = false
    console.warn(error)
  })
}


//获取字典
const getDic = () => {
  store.getDicData('health_rule_big_type').then((res) => {
    const item = getObjectByKey(fromItems.value, 'prop', 'bigType')
    if (item && item.type === 'selete') {
      item.seleteData = transfDicArrData(res)
    }
  })
  store.getDicData('small_type').then((res) => {
    const item = getObjectByKey(fromItems.value, 'prop', 'smallType')
    if (item && item.type === 'selete') {
      smallTypeList.value = transfDicArrData(res)
      item.seleteData = smallTypeList.value
    }
  })
  store.getDicData('business_type').then((res) => {
    const item = getObjectByKey(fromItems.value, 'prop', 'businessType')
    if (item && item.type === 'selete') {
      item.seleteData = transfDicArrData(res)
    }
  })
}

//选择的
const tableData = ref<Array<icCodeLists>>([...(formData.icdCodeList ? formData.icdCodeList : [])])
//选项
const tableDatas = ref<Array<icCodeLists>>([])
//显示选项
const showSeleteDialog = ref(false)
// 操作按钮数据
const operationDataDelete: Array<Opr> = [
  {code: 'delete', label: '删除', iconConfig: {icon: 'common-delete', type: 'custom', color: ColorRed, size: 20}}
]

// 操作按钮数据
const operationDataAdd: Array<Opr> = [
  {code: 'add', label: '添加', iconConfig: {icon: 'common-swap-add', type: 'custom', color: ColorTheme, size: 20}}
]
//添加数据
const baseAdd = {
  icdCode: '',
  icdCodeName: '',
  oper: [],
  id:undefined
}
//表格数据
const tableHeaderData = ref<Array<HeaderData>>([
  {prop: 'icdCode', label: 'ICD-10编码', columnType: 'slot', 'min-width': '100'},
  {prop: 'icdCodeName', label: '疾病名称', columnType: 'slot', 'min-width': '100'},
  {prop: 'oper', label: '操作', columnType: 'slot', 'width': '80'}
])
//表格数据
const tableHeaderDatas = ref<Array<HeaderData>>([
  {prop: 'icdCode', label: 'ICD-10编码', columnType: 'text', 'min-width': '100'},
  {prop: 'icdCodeName', label: '疾病名称', columnType: 'text', 'min-width': '100'}
])
//添加展示按钮
const showButton = (dataList:Array<icCodeLists>) => {
  const returnList:Array<icCodeLists&RowOperbuttons> = []
  if (!dataList.length) {
    const newAdd = JSON.parse(JSON.stringify(baseAdd))
    dataList.push(newAdd)
  }
  dataList.map((item, index) => {
    returnList.push({...item, oper:index === (dataList.length - 1) ? [...operationDataAdd, ...operationDataDelete] : operationDataDelete})
  })
  return returnList
}

// 添加事件
const onAdd = () => {
  const addData = JSON.parse(JSON.stringify(baseAdd))
  tableData.value.push(addData)
  tableData.value = showButton(tableData.value)
}

// 删除事件
const onRemove = (index: number) => {
  tableData.value.splice(index, 1)
  tableData.value = showButton(tableData.value)
}

// 操作栏点击
const onErtion = (code, row) => {
  if (code === 'delete') {
    onRemove(tableData.value.indexOf(row))
  } else if (code === 'add') {
    onAdd()
  }
}

const isShowSearch = ref(false)
const currRow = ref<icCodeLists>()
const tableDatasLoading = ref<boolean>(false)
const onSearch = (flag:string, info:string, row) => {
  currRow.value = row

  isShowSearch.value = true
  tableDatas.value.length = 0
  tableDatasLoading.value = true
  const params = flag === 'code' ? {icdCode:info} : {icdCodeName:info}

  getCodeList(params).then((res) => {
    const {data} = res.data
    data.map((item) => {
      tableDatas.value.push(item)
    })
    tableDatasLoading.value = false
  }).catch(() => {
    tableDatasLoading.value = false
  })

}

//选中单个疾病编码和名称
const onRowClick = (row) => {
  isShowSearch.value = false
  if (currRow.value) {
    tableData.value[tableData.value.indexOf(currRow.value)] = {
      ...tableData.value[tableData.value.indexOf(currRow.value)],
      id : row.id,
      icdCode : row.icdCode,
      icdCodeName:row.icdCodeName
    }
  }
}

// icdcode弹窗关闭
const onIcdCodesClose = () => {
  showSeleteDialog.value = false
}

// icdcode弹窗取消
const onIcdCodesCancel = () => {
  onIcdCodesClose()
}

// icdcode弹窗保存
const onConfirmSelete = () => {
  formData.icdCodeList = tableData.value || []
  formData.icdCodes = formData.icdCodeList.map(item => item.icdCodeName).join(',')

  onIcdCodesClose()
}

// icdcode点击
const onIcdCodesClick = () => {
  showSeleteDialog.value = true
  tableData.value = showButton(tableData.value)
}

onBeforeMount(() => {
  getDic()
  initTitle()
})

</script>

<template>
  <!-- 新增/编辑健教指导 -->
  <d-dialog
    :title="title"
    width="600px"
    :show-dialog="showDialog"
    :show-save-loading="showSaveLoading"
    @cancel="onCancel"
    @confirm="onConfirm"
    @close="onClose"
  >
    <d-from
      label-position="right"
      :label-width="100"
      :reset-fields-flag="resetFieldsFlag"
      :validate-flag="validateFlag"
      :rules="rules"
      method="post"
      :form-data="formData"
      :form-items="fromItems"
      :form-line-num="1"
      :clear-empty="false"
      @submit="onSubmit"
    >
      <template #codeList>
        <el-input
          v-model="formData.icdCodes"
          :style="{width:'457px',backgroundColor:'#eee'}"
          :readonly="true"
          @click="onIcdCodesClick"
        />
      </template>
    </d-from>
  </d-dialog>

  <!-- ICD-10编码列表 -->
  <d-dialog
    v-if="showSeleteDialog"
    :show-dialog="showSeleteDialog"
    title="选择ICD-10编码"
    width="500px"
    @cancel="onIcdCodesCancel"
    @confirm="onConfirmSelete"
    @close="onIcdCodesClose"
  >
    <div :style="{height:'300px'}">
      <d-table
        ref="main"
        style="min-height: 300px"
        :table-data="tableData"
        :table-header-data="tableHeaderData"
      >
        <template #icdCode="scope">
          <el-input v-model="scope.row['icdCode']" @keyup.enter="onSearch('code',scope.row['icdCode'],scope.row)" @input="scope.row['icdCodeName']=''" />
        </template>
        <template #icdCodeName="scope">
          <el-input v-model="scope.row['icdCodeName']" @keyup.enter="onSearch('name',scope.row['icdCodeName'],scope.row)" @input="scope.row['icdCode']=''" />
        </template>
        <template #oper="scope">
          <operation
            :row="scope.row"
            :col="scope.item"
            @opertion-click="onErtion"
          />
        </template>
      </d-table>
    </div>

    <!-- 选择ICD-10编码 -->
    <d-table
      v-if="isShowSearch"
      ref="search"
      :style="{minHeight: '200px'}"
      :table-data="tableDatas"
      :table-header-data="tableHeaderDatas"
      :show-loading="tableDatasLoading"
      @row-click="onRowClick"
    />
  </d-dialog>
</template>

<style scoped>
</style>